package com.zyw.security.shiro.web.session;

import com.zyw.cache.j2cache.J2Cache;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Collection;

/**
 * 基于 j2cache 实现的 sessionDao
 *
 * @author zhangyw
 * @date 2018/1/10 15:48
 */
public class ShiroJ2CacheSessionDao extends AbstractSessionDAO {

    private static final Logger logger = LoggerFactory.getLogger(ShiroJ2CacheSessionDao.class);

    private static final String session_region = "session";

    public ShiroJ2CacheSessionDao() {
        super();
        setSessionIdGenerator(new UUIDSessionIdGenerator());
    }

    @Override
    protected Serializable generateSessionId(Session session) {
        if (this.getSessionIdGenerator() == null) {
            String msg = "sessionIdGenerator attribute has not been configured.";
            throw new IllegalStateException(msg);
        } else {
            return this.getSessionIdGenerator().generateId(session);
        }
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = getSessionId(session);
        assignSessionId(session, sessionId);
        J2Cache.getChannel().set(session_region, sessionId, session);
        if (logger.isTraceEnabled()) {
            logger.trace("create session:{}", sessionId);
        }
        return sessionId;
    }

    private Serializable getSessionId(Session session) {
        return generateSessionId(session);
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if (logger.isTraceEnabled()) {
            logger.trace("read session:{}", sessionId);
        }
        return (Session) J2Cache.getChannel().get(session_region, sessionId).getValue();
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        J2Cache.getChannel().set(session_region, session.getId(), session);
        if (logger.isTraceEnabled()) {
            logger.trace("update session:{}", session.getId());
        }
    }

    @Override
    public void delete(Session session) {
        J2Cache.getChannel().evict(session_region, session.getId());
        if (logger.isTraceEnabled()) {
            logger.trace("delete session:{}", session.getId());
        }
    }

    @Override
    public Collection<Session> getActiveSessions() {
        throw new UnsupportedOperationException("Unsupported getActiveSessions");
    }
}
